package com.aisile.user.service.impl;

import com.aisile.common.exception.CustomExceptionCatch;
import com.aisile.common.yongyou.YongYouCommonUtils;
import com.aisile.model.common.dtos.PageResponseResult;
import com.aisile.model.common.dtos.ResponseResult;
import com.aisile.model.common.enums.AppHttpCodeEnum;
import com.aisile.model.user.dtos.AuthDto;
import com.aisile.model.user.pojos.ApUserRealname;
import com.aisile.user.mapper.ApUserRealnameMapper;
import com.aisile.user.service.ApUserRealnameService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @Auther:yry
 * @Date:2023/12/27 0027
 * @VERSON:1.0
 */
@Service
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {

    @Autowired
    private YongYouCommonUtils yongYouCommonUtils;


    @Override
    public ResponseResult loadListByStatus(AuthDto dto) {
        if(dto == null){
            CustomExceptionCatch.catchApp(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        // 分页初始化
        dto.checkParam();
        // 构建查询条件
        LambdaQueryWrapper<ApUserRealname> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if(dto.getStatus() == null){  //状态 0 1 2 3 9
            // 需要初始化成 3 默认展示待人工审核列表
            dto.setStatus((short)3);
        }
        if((dto.getStatus()>=(short)0 && dto.getStatus()<=(short)3) || (dto.getStatus().equals((short)9))){
            lambdaQueryWrapper.eq(ApUserRealname::getStatus,dto.getStatus());
        }else{
            CustomExceptionCatch.catchApp(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        // 没有任何问题，直接调用查询即可
        IPage<ApUserRealname> iPage =  this.page(new Page<>(dto.getPage(),dto.getSize()),lambdaQueryWrapper);
        ResponseResult responseResult = new PageResponseResult(dto.getPage(),dto.getSize(),((Long)iPage.getTotal()).intValue());
        responseResult.setData(iPage.getRecords());
        return responseResult;
    }

    @Override
    public ResponseResult updateStatusById(AuthDto dto, Short type) {
        if (dto == null || dto.getId() == null) {
            CustomExceptionCatch.catchApp(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        ApUserRealname apUserRealname = this.getById(dto.getId());
        if (apUserRealname == null) {
            CustomExceptionCatch.catchApp(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        if (dto.getMsg() != null) {
            apUserRealname.setReason(dto.getMsg());
        }
        apUserRealname.setStatus(type);
        this.updateById(apUserRealname);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public void autoUpdateStatusById(AuthDto dto) {
        // 无脑判断
        if (dto == null || dto.getId() == null) {
            return;
        }
        // 根据id 查询认证信息  根据状态进行审核 只有状态  = 1 的才可以
        ApUserRealname apUserRealname = this.getById(dto.getId());

        if (apUserRealname != null && apUserRealname.getStatus().equals((short) 1)) {
            // 可以验证  1. ocr 识别   2. 二要素认证   3. 活体  4. 人证
            int i = 0; // 0 全成功  失败 --  成功 ++
            // 调用 ocr
            Map<String, Object> map = yongYouCommonUtils.IdcardOCR(apUserRealname.getFontImage());
            if (map == null){
                return;
            }
            String name = (String) map.get("name");
            String cardNum = (String) map.get("cardNum");
            if(name == null || cardNum ==null){
                // 修改数据状态 直接就失败
                dto.setMsg("身份信息识别失败");
                this.updateStatusById(dto, (short) 2);
                return;
            }
            // 二要素
            if (!yongYouCommonUtils.matchIdentity(cardNum,name)) {
                dto.setMsg("身份信息核验失败");
                this.updateStatusById(dto, (short) 2);
                return;
            }
            // 活体
            int biologicalexaminationNo =  yongYouCommonUtils.biologicalexamination(apUserRealname.getLiveImage(),2);
            if(biologicalexaminationNo <0){
                dto.setMsg("人脸信息识别失败");
                this.updateStatusById(dto, (short) 2);
                return;
            }else if(biologicalexaminationNo >0){
                i++;
            }

            // 人证核验

            // 统一判断
            if(i == 0){
                //成功
                this.updateStatusById(dto, (short) 9);
            }else{
                //疑似  才需要人工介入
                this.updateStatusById(dto, (short) 3);
            }
        }

    }

    @Override
    public ResponseResult saveRealname(ApUserRealname apUserRealname) {

        // 保存数据库了

        // 触发 自动审核代码
        // 发送rabbitMQ消息
//

//        AuthDto authDto = new AuthDto();
//        authDto.setId(apUserRealname.getId());
//        this.autoUpdateStatusById(authDto);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
